package com.qikux.utils;

import javax.servlet.http.Part;
import java.io.File;
import java.util.UUID;

public class UploadUtils {

    private static PropUtils propUtils = PropUtils.getInstance("/upload.properties");

    /**
     * 上传文件
     * @param part
     * @param property
     * @return
     * @throws Exception
     */
    public static String upload(Part part,String property) throws Exception {

        //String parent = propUtils.getProperty(property);
        String parent = property;
        if("upload.res.dir".equals(property)){
            parent = propUtils.getProperty(property);
        }
        // 生成一个随机的用户头像名称
        String uuid = UUID.randomUUID().toString();

        File file = new File(parent,uuid);
        // 保证目录是存在的
        file.getParentFile().mkdirs();
        part.write(file.getCanonicalPath());

        return uuid;
    }

    /**
     * 删除文件
     * @param property
     * @param fileName
     */
    public static void delete(String property,String fileName){
        File file = findFile(property, fileName);
        if (file.exists()) file.delete();
    }

    public static File findFile(String property,String photo) {
        String parent = property;
        if("upload.res.dir".equals(property)){
            parent = propUtils.getProperty(property);
        }
        return new File(parent,photo);
    }
}
